<?php

namespace App\Http\Controllers\Guard\Article;

use App\Http\Controllers\Common\GuardController;
use App\Models\Article\ArticleClassify;
use App\Models\Article\ArticleInfo;
use App\Models\Article\ArticleInfoReview;
use App\Models\Constant\Constant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class ArticleInfoController extends GuardController {

    public function change(Request $request) {
        $id = $request->input('id',0);
        if($request->has('status')){
            ArticleInfo::whereIn('id',$id)->update(['status'=>$request->input('status')]);
        }elseif($request->has('is_top')){
            ArticleInfo::where('id',$id)->update(['is_top'=>$request->input('is_top')]);
        } else{

        }
        return responseSuccess();

    }

    public function lst(Request $request) {
        $classifies = ArticleClassify::pluck('name','id')->toArray();
        try{
            $page = $request->input('page',1);
            $pageSize = $request->input('pageSize',Constant::PAGE_SIZE);
            $title = $request->input('title','');
            $keyWord = $request->input('keyWord','');
            $classifyId = $request->input('classifyId','all');
            $createdAt = $request->input('createdAt',null);
            $conditions = compact('keyWord','classifyId','title','createdAt');
            $conditions['orderBy']['col'] = 'sort';
            $conditions['orderBy']['sort'] = 'desc';

            $records = (new ArticleInfo)->getLst($conditions)
                ->with(['getGuardUser:id,name'])
                ->paginate($pageSize,['*'],'page',$page);
            foreach ($records as $record) {
                $record->description = Str::limit($record->description,20);
                $record->content = Str::limit($record->content,20);
                $record->status_name = $record->status==1?'是':'否';
                $record->is_top_name = $record->is_top==1?'是':'否';
                $record->classify_name = $classifies[$record->classify_id]??'未知';
                $record->content = Str::limit($record->content,50);
            }
            return responseSuccess($records->items(),$records->total());
        }catch(\Exception $e){
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            return responseFail($tip);
        }
    }

    public function add(Request $request) {

        $this->validate($request, [
            'title'=>'required|min:1|max:50',
            'cover_url'=>'required',
            'content'=>'required',
            //'key_word'=>'required',
            //'sign'=>'required',
            'description'=>'required'
        ],[],[
            'title'=>'资讯标题',
            'cover_url'=>'封面',
            'content'=>'内容',
            //'key_word'=>'关键字',
            //'sign'=>'标签',
            'description'=>'摘要',
        ]);


        try{
            $id = $request->input('id',0);
            $info = $request->input();

            if(isset($info['sign'])){
                $info['sign'] = Str::replace(',', '，', $info['sign']);
            }
            if(isset($info['key_word'])){
                $info['key_word'] = Str::replace(',', '，', $info['key_word']);
            }


            $token = $request->header('token');
            if(empty($token)) return responseFail('获取token失败！');
            $guard_user_id = checkJWT($token)['id']??0;
            if($guard_user_id<=0){
                return responseFail('获取当前用户失败！');
            }
            $info['guard_user_id'] = $guard_user_id;
            $records = ArticleInfo::updateOrCreate(compact('id'),$info);
            return responseSuccess($records->toArray());
        }catch(\Exception $e){
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            return responseFail($tip);
        }
    }

    public function addReview(Request $request) {

        $this->validate($request, [
            'title'=>'required|min:1|max:50',
            'cover_url'=>'required',
            'content'=>'required',
            //'key_word'=>'required',
            //'sign'=>'required',
            'description'=>'required'
        ],[],[
            'title'=>'资讯标题',
            'cover_url'=>'封面',
            'content'=>'内容',
            //'key_word'=>'关键字',
            //'sign'=>'标签',
            'description'=>'摘要',
        ]);


        try{
            $id = $request->input('id',0);
            $info = $request->input();

            if(isset($info['sign'])){
                $info['sign'] = Str::replace(',', '，', $info['sign']);
            }
            if(isset($info['key_word'])){
                $info['key_word'] = Str::replace(',', '，', $info['key_word']);
            }


            $token = $request->header('token');
            if(empty($token)) return responseFail('获取token失败！');
            $guard_user_id = checkJWT($token)['id']??0;
            if($guard_user_id<=0){
                return responseFail('获取当前用户失败！');
            }
            $info['guard_user_id'] = $guard_user_id;
            $records = ArticleInfoReview::updateOrCreate(compact('id'),$info);
            return responseSuccess($records->toArray());
        }catch(\Exception $e){
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            return responseFail($tip);
        }
    }

    public function getRecord(Request $request) {
        $id = $request->input('id',0);
        $record = ArticleInfo::find($id);
        $record->url = asset($record->cover_url);
        return responseSuccess([$record->toArray()],1);
    }

    public function del(Request $request) {

        $ids = $request->input('ids');

        if(!is_array($ids)){
            $ids = [$ids];
        }
        ArticleInfo::whereIn('id',$ids)->delete();
        return responseSuccess();
    }

    public function uploadVideo(Request $request) {
        $fileKeys = array_keys($request->file());
        foreach ($fileKeys as $fileKey) {
            $file = $request->file($fileKey);
            $ext = $file->getClientOriginalExtension();
            $middlePath = "/article/".date('Y-m-d');
            $absDir = Storage::disk('upload')->path($middlePath);
            if(!is_dir($absDir)){mkdir($absDir,0777,true);}
            $fileName = time().uniqid().".$ext";
            $filePath = $file->storeAs($middlePath,$fileName,'upload');
            $filePath = '/storage/upload/'.$filePath;
            $info= [
                'url'=>asset($filePath),
            ];
            return response()->json([
                'data'=>$info,
                'errno'=>0
            ]);
        }
    }

    public function uploadImg(Request $request) {
        $fileKeys = array_keys($request->file());
        $info = [];
        foreach ($fileKeys as $fileKey) {
            $file = $request->file($fileKey);
            $ext = $file->getClientOriginalExtension();
            $middlePath = "/article/".date('Y-m-d');
            $absDir = Storage::disk('upload')->path($middlePath);
            if(!is_dir($absDir)){mkdir($absDir,0777,true);}
            $fileName = time().uniqid().".$ext";
            $filePath = $file->storeAs($middlePath,$fileName,'upload');
            $filePath = '/storage/upload/'.$filePath;
            $info[] = [
                'url'=>asset($filePath),
                'atl'=>'图片',
                'href'=>''
            ];

        }
        return response()->json([
            'data'=>$info,
            'errno'=>0
        ]);

    }

}
